import {
  asyncRoutes,
  constantRoutes
} from '@/router'
const state = {
  routes: [],
  nowPath: {},
  pageRule: [],
  pageRuleArr: [],

}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_NOWPATH: (state, nowPath) => {
    state.nowPath = nowPath;
  },
  SET_RULEARR: (state, pageRuleArr) => {
    state.pageRuleArr = pageRuleArr;
  },
}
/*
    将路由与映射表关联
*/
function mapList(router, menu) {
  const res = [];
  router.forEach(e => {
    let t = {
        ...e
      },
      m = getMenu(t.name, menu);
    if (m || t.hidden) {
      if (!t.hidden && m.children.length != 0 && t.children && t.children.length != 0) {
        t.children = mapList(t.children, m.children)
      }
      // 显示后端返回的菜单名称
      t.meta.title = m.name;
      res.push(t)
    }
  })
  return res;
}

/* 获取 返回菜单数据与路由对应的数据 */
function getMenu(name, menu) {
  let res = null;
  menu.forEach(e => {
    if (e.code == name) {
      res = e;
    }
  })
  return res;
}
/*
  初始化路由数据对应的 rulesPath
*/
function routerBuding(router, kename = '') {
  const res = [];
  router.forEach(e => {
    let t = {
      ...e
    }
    let name = kename ? `${kename}:` : kename
    t.rulesPath = `${name}${t.name}`
    if (t.children) {
      t.children = routerBuding(t.children, t.rulesPath)
    }
    res.push(t)
  })
  return res;
}

const actions = {
  generateRoutes({
    commit,
    dispatch
  }, menu) {
    return new Promise(async resolve => {
      let accessedRoutes = mapList(routerBuding(asyncRoutes), menu);
      commit('SET_ROUTES', accessedRoutes);
      accessedRoutes = accessedRoutes.concat([{
        path: '*',
        component: () => import('@/views/404'),
        redirect: '/404'
      }])
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
